import 'dart:async';
import 'dart:math';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:provider/provider.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import '../core/theme_config.dart';
import '../services/remote_control_service.dart';

import '../core/sites.dart';
import '../core/api_service.dart';
import '../core/models.dart';
import '../core/douban_service.dart';
import '../core/auth_store.dart';
import 'detail_page.dart';
import '../core/history.dart';
import 'nba_page.dart';
import 'live_page.dart';
import 'search_page.dart';
import 'profile_page.dart';
import 'shortplay_page.dart';
import '../utils/util.dart';

class _NavItem {
  final IconData icon;
  final String label;
  final String? keyword;
  const _NavItem(this.icon, this.label, {this.keyword});
}

class _AppScrollBehavior extends MaterialScrollBehavior {
  const _AppScrollBehavior();
  @override
  Set<PointerDeviceKind> get dragDevices => {
        PointerDeviceKind.touch,
        PointerDeviceKind.mouse,
        PointerDeviceKind.stylus,
      };
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  VideoSite _currentSite = VideoSite(id: 'local', name: '默认', api: '', detail: '', isAdult: false);
  late ApiService _service;
  final _searchController = TextEditingController();
  final _searchFocus = FocusNode();
  final ScrollController _navScroll = ScrollController();
  final ScrollController _filterScroll = ScrollController();
  List<String> _searchHistory = [];
  List<PlayHistoryItem> _playHistory = [];
  // 首页四栏数据
  List<VodItem> _hotMovies = [];
  List<VodItem> _hotTv = [];
  List<VodItem> _hotVariety = [];
  List<VodItem> _hotAnime = [];
  List<VodItem> _hotKorean = [];
  List<VodItem> _top250Movies = [];
  List<VodItem> _items = [];
  
  // 轮播图数据
  List<VodItem> _carouselItems = [];
  bool _loading = false;
  int _page = 1;
  String? _keyword;
  int _selectedNav = 0;
  // 电影页面分类状态
  String _movieCategory = '热门电影'; // 默认显示热门电影
  final _navItems = const [
    _NavItem(Icons.recommend, '推荐'),
    _NavItem(Icons.movie_rounded, '电影', keyword: '电影'),
    _NavItem(Icons.tv_rounded, '剧集', keyword: '剧'),
    _NavItem(Icons.theaters_rounded, '综艺', keyword: '综艺'),
    _NavItem(Icons.animation_rounded, '动漫', keyword: '动漫'),
    _NavItem(Icons.sports_baseball_rounded, '体育'),
    _NavItem(Icons.live_tv_rounded, '电视'),
    _NavItem(Icons.playlist_play_rounded, '韩剧'),
  ];

  @override
  void initState() {
    super.initState();
    _initializeApp();
  }

  Future<void> _initializeApp() async {
    // 先加载站点数据
    await SitesRepository.loadSites();
    
    // 初始化当前站点
    _currentSite = kVideoSites.isNotEmpty ? kVideoSites.first : VideoSite(id: 'local', name: '默认', api: '', detail: '', isAdult: false);
    _service = ApiService(_currentSite);
    
    _load(reset: true);
    _loadHomeSections();
    _checkVersionOnStartup();
  }

  @override
  void dispose() {
    _navScroll.dispose();
    _filterScroll.dispose();
    _searchController.dispose();
    _searchFocus.dispose();
    super.dispose();
  }

  Future<void> _loadHomeSections() async {
    try {
      // 使用并发模式加载首页五栏，为每个请求设置超时与错误兜底
      final stopwatch = Stopwatch()..start();
      final futures = <Future<List<VodItem>>>[
        DoubanService.fetchHotMoviesGet().timeout(const Duration(seconds: 3)).catchError((_) => <VodItem>[]),
        DoubanService.fetchHotTv().timeout(const Duration(seconds: 3)).catchError((_) => <VodItem>[]),
        DoubanService.fetchHotVariety().timeout(const Duration(seconds: 3)).catchError((_) => <VodItem>[]),
        DoubanService.fetchHotAnime().timeout(const Duration(seconds: 3)).catchError((_) => <VodItem>[]),
        DoubanService.fetchHotKorean().timeout(const Duration(seconds: 3)).catchError((_) => <VodItem>[]),
      ];
      final res = await Future.wait(futures, eagerError: true);
      
      // 获取轮播图数据：随机从每个分类中取一个影视
      final random = Random();
      final carouselItems = [
        if (res[0].isNotEmpty) res[0][random.nextInt(res[0].length)],
        if (res[1].isNotEmpty) res[1][random.nextInt(res[1].length)],
        if (res[2].isNotEmpty) res[2][random.nextInt(res[2].length)],
        if (res[3].isNotEmpty) res[3][random.nextInt(res[3].length)],
        if (res[4].isNotEmpty) res[4][random.nextInt(res[4].length)],
      ];
      
      setState(() {
        _hotMovies = (res.length > 0 ? res[0] : const <VodItem>[]).take(12).toList();
        _hotTv = (res.length > 1 ? res[1] : const <VodItem>[]).take(12).toList();
        _hotVariety = (res.length > 2 ? res[2] : const <VodItem>[]).take(12).toList();
        _hotAnime = (res.length > 3 ? res[3] : const <VodItem>[]).take(12).toList();
        _hotKorean = (res.length > 4 ? res[4] : const <VodItem>[]).take(12).toList();
        _carouselItems = carouselItems;
      });
      print('首页五栏并发加载耗时: ${stopwatch.elapsedMilliseconds} ms');
    } catch (_) {}
  }

  Future<void> _checkVersionOnStartup() async {
    await CommonUtils.checkAndPromptUpdate(context, manual: false);
  }


  Future<void> _load({bool reset = false}) async {
    if (_loading) return;
    setState(() => _loading = true);
    try {
      if (reset) {
        _page = 1;
        _items = [];
      }
      final kw = _keyword;
      if (kw != null && kw.trim().isNotEmpty) {
        // 记录搜索历史
        // await _saveSearchHistory(kw);
        
        // 只使用豆瓣搜索API
        print('开始豆瓣搜索：$kw');
        final list = await DoubanService.searchMovies(
          query: kw, 
          start: (_page - 1) * 10, 
          count: 10
        ).catchError((_) => <VodItem>[]);
        
        print('豆瓣搜索完成，结果数量：${list.length}');
        setState(() {
          _items.addAll(list);
          _page += 1;
        });
        // 列表补图：对没有图片的条目，拉取详情补充封面（并行，限速）
        _fillMissingPosters(list);
      } else {
        // 处理豆瓣数据的分页加载
        List<VodItem> list = [];
        if (_selectedNav == 1) {
          if (_movieCategory == 'Top250') {
            // Top250支持真正的分页
            final start = _items.length; // 使用当前已加载的数量作为start
            list = await DoubanService.fetchTop250Movies(start: start, count: 10);
          }else{
             // 热门电影支持分页
          final start = _items.length; // 使用当前已加载的数量作为start
          list = await DoubanService.fetchHotMoviesGet(pageStart: start, pageLimit: 10);               
          }           
        } else if (_selectedNav == 2 && _items == _hotTv) {
          // 剧集页面 - 热门剧集支持分页
          final pageStart = _items.length; // 使用当前已加载的数量作为page_start
          list = await DoubanService.fetchHotTv(pageStart: pageStart, pageLimit: 10);
        } else if (_selectedNav == 3 && _items == _hotVariety) {
          // 综艺页面 - 热门综艺支持分页
          final pageStart = _items.length; // 使用当前已加载的数量作为page_start
          list = await DoubanService.fetchHotVariety(pageStart: pageStart, pageLimit: 10);
        } else if (_selectedNav == 4 && _items == _hotAnime) {
          // 动漫页面 - 热门动漫支持分页
          final pageStart = _items.length;
          list = await DoubanService.fetchHotAnime(pageStart: pageStart, pageLimit: 10);
        } else if (_selectedNav == 7 && _items == _hotKorean) {
          // 韩剧页面 - 热门韩剧支持分页
          final pageStart = _items.length;
          list = await DoubanService.fetchHotKorean(pageStart: pageStart, pageLimit: 10);
        }
        
        if (list.isNotEmpty) {
          setState(() {
            _items.addAll(list);
            _page += 1;
          });
          _fillMissingPosters(list);
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载失败: $e')),
        );
      }
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  Future<void> _fillMissingPosters(List<VodItem> batch) async {
    final need = batch.where((e) => (e.pic == null || e.pic!.isEmpty)).take(12).toList();
    if (need.isEmpty) return;
    try {
      final futures = need.map((e) async {
        // 使用当前站点查详情
        final detail = await _service.fetchDetail(e.id);
        return VodItem(
          id: e.id,
          name: e.name,
          typeName: e.typeName,
          pic: detail.pic ?? e.pic,
          remarks: e.remarks,
          actor: e.actor,
          director: e.director,
          area: e.area,
          year: e.year,
        );
      }).toList();
      final updated = await Future.wait(futures);
      // 用新条目替换到 _items
      setState(() {
        for (final u in updated) {
          final idx = _items.indexWhere((it) => it.id == u.id && it.name == u.name);
          if (idx >= 0) {
            _items[idx] = u;
          }
        }
      });
    } catch (_) {}
  }

  void _doSearch() {
    _keyword = _searchController.text.trim().isEmpty
        ? null
        : _searchController.text.trim();
    _load(reset: true);
  }

  void _navigateToSearchPage() {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => const SearchPage(),
      ),
    );
  }

  void _navigateToProfilePage() {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => const ProfilePage(),
      ),
    );
  }

  void _tapNav(int index) {
    setState(() => _selectedNav = index);
    final navItem = _navItems[index];
    if (index == 0) {
      // 首页：清空搜索，重置状态，不调用_load
      _searchController.clear();
      _keyword = null;
      setState(() {
        _items = [];
        _page = 1;
      });
      return;
    }
    
    if (navItem.label == '记录') {
      // 记录页面：清空搜索，重置状态
      _searchController.clear();
      _keyword = null;
      setState(() {
        _items = [];
        _page = 1;
      });
      return;
    }
    
    // 使用豆瓣服务数据而不是关键词搜索
    if (navItem.label == '电影') {
      setState(() {
        _movieCategory = '热门电影'; // 重置为默认分类
        _items = _hotMovies;
        _keyword = null;
      });
      return;
    }
    if (navItem.label == '剧集') {
      setState(() {
        _items = _hotTv;
        _keyword = null;
      });
      return;
    }
    if (navItem.label == '综艺') {
      setState(() {
        _items = _hotVariety;
        _keyword = null;
      });
      return;
    }
    if (navItem.label == '动漫') {
      setState(() {
        _items = _hotAnime;
        _keyword = null;
      });
      return;
    }
    if (navItem.label == '韩剧') {
      setState(() {
        _items = _hotKorean;
        _keyword = null;
      });
      return;
    }

    // 其他情况（如纪录）仍使用关键词搜索
    final kw = navItem.keyword;
    if (kw != null && kw.isNotEmpty) {
      _searchController.text = kw;
      _doSearch();
    }
  }

  void _goToMenu(String label) {
    final idx = _navItems.indexWhere((e) => e.label == label);
    if (idx >= 0) {
      _tapNav(idx);
    }
  }
  
  /// 处理首页特定的按键事件
  void _handleHomeKeyEvent(LogicalKeyboardKey key) {
    // 数字键快捷导航到对应标签页
    if (key == LogicalKeyboardKey.digit1) {
      _tapNav(0); // 推荐
    } else if (key == LogicalKeyboardKey.digit2) {
      _tapNav(1); // 电影
    } else if (key == LogicalKeyboardKey.digit3) {
      _tapNav(2); // 剧集
    } else if (key == LogicalKeyboardKey.digit4) {
      _tapNav(3); // 综艺
    } else if (key == LogicalKeyboardKey.digit5) {
      _tapNav(4); // 动漫
    } else if (key == LogicalKeyboardKey.digit6) {
      _tapNav(5); // NBA
    } else if (key == LogicalKeyboardKey.digit7) {
      _tapNav(6); // 直播
    }else if (key == LogicalKeyboardKey.digit8) {
      _tapNav(7); // 韩剧
    }
    
    // 媒体控制键
    else if (key == LogicalKeyboardKey.mediaPlayPause) {
      // 可以在这里添加播放/暂停逻辑
      debugPrint('播放/暂停按键');
    }
  }

  @override
  Widget build(BuildContext context) {
    final isWide = MediaQuery.of(context).size.width >= 1000;
    final remoteService = RemoteControlService();
    
    return RawKeyboardListener(
      focusNode: FocusNode(),
      autofocus: true,
      onKey: (event) {
        if (remoteService.handleKeyEvent(event)) {
          // 按键已被处理
          return;
        }
        
        // 添加首页特定的按键处理
        if (event is RawKeyDownEvent) {
          _handleHomeKeyEvent(event.logicalKey);
        }
      },
      child: Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: Provider.of<ThemeConfig>(context).currentGradient,
        ),
        child: SafeArea(
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              if (isWide)
                Container(
                  width: 200,
                  padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Padding(
                        padding: EdgeInsets.symmetric(vertical: 8.0),
                        child: Text('Stars_Moon', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600)),
                      ),
                      const SizedBox(height: 8),
                      ...List.generate(_navItems.length, (i) {
                        final it = _navItems[i];
                        final selected = i == _selectedNav;
                        return Padding(
                          padding: const EdgeInsets.symmetric(vertical: 4.0),
                          child: InkWell(
                            borderRadius: BorderRadius.circular(8),
                            onTap: () => _tapNav(i),
                            child: Container(
                              padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 12),
                              decoration: BoxDecoration(
                                color: selected ? Colors.white : Colors.transparent,
                                borderRadius: BorderRadius.circular(8),
                              ),
                              child: Row(
                                children: [
                                  Icon(it.icon, size: 20, color: selected ? Colors.blueAccent : Colors.black54),
                                  const SizedBox(width: 10),
                                  Expanded(child: Text(it.label)),
                                ],
                              ),
                            ),
                          ),
                        );
                      }),
                    ],
                  ),
                ),
              Expanded(
                child: Column(
                  children: [
                      Padding(
                        padding: const EdgeInsets.fromLTRB(12, 8, 12, 6),
                        child: Builder(builder: (context) {
                          final isCompact = MediaQuery.of(context).size.width < 600;
                          return Row(
                            children: [
                              const SizedBox(width: 8),
                              Expanded(
                                child: TextField(
                                  controller: _searchController,
                                  focusNode: _searchFocus,
                                  maxLines: 1,
                                  readOnly: true, // 设置为只读，防止键盘弹出
                                  decoration: InputDecoration(
                                    hintText: '搜索电影、电视剧、综艺…',
                                    isDense: true,
                                    filled: true,
                                    fillColor: Colors.white,
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(20),
                                      borderSide: BorderSide.none,
                                    ),
                                    contentPadding: const EdgeInsets.symmetric(vertical: 10, horizontal: 12),
                                    prefixIcon: const Icon(Icons.search_rounded, size: 18),
                                  ),
                                  onTap: () => _navigateToSearchPage(), // 点击时跳转到搜索页面
                                  onSubmitted: (_) => _doSearch(),
                                ),
                              ),
                              const SizedBox(width: 6),
                               // 我的按钮
                                IconButton(
                                  onPressed: () => _navigateToProfilePage(),
                                  icon: const Icon(Icons.person_rounded),
                                  tooltip: '我的',
                                )
                            ],
                          );
                        }),
                      ),
                    // 窄屏顶部菜单栏：改为标签样式，区分于筛选关键词
                    if (!isWide)
                      ScrollConfiguration(
                        behavior: const _AppScrollBehavior(),
                        child: SingleChildScrollView(
                          controller: _navScroll,
                          scrollDirection: Axis.horizontal,
                          physics: const BouncingScrollPhysics(),
                          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                          child: Row(
                            children: List.generate(_navItems.length, (i) {
                              final it = _navItems[i];
                              final selected = i == _selectedNav;
                              return Padding(
                                padding: const EdgeInsets.only(right: 12.0),
                                child: InkWell(
                                  onTap: () => _tapNav(i),
                                  borderRadius: BorderRadius.circular(8),
                                  child: Container(
                                    padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
                                    decoration: BoxDecoration(
                                      border: Border(bottom: BorderSide(color: selected ? Colors.blueAccent : Colors.transparent, width: 2)),
                                    ),
                                    child: Row(
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        Icon(it.icon, size: 16, color: selected ? Colors.blueAccent : Colors.black54),
                                        const SizedBox(width: 6),
                                        Text(it.label, overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: selected ? FontWeight.w600 : FontWeight.w400)),
                                      ],
                                    ),
                                  ),
                                ),
                              );
                            }),
                          ),
                        ),
                      ),
                    const SizedBox(height: 8),
                    ..._buildMainContent(isWide),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
      )
    );
  }

  List<Widget> _buildMainContent(bool isWide) {
    // 体育页面：在主内容区域展示体育内容
    if (_selectedNav == 5) {
      return [
        Expanded(
          child: NbaPage(),
        )
      ];
    }
     
    // 直播页：在主内容区域展示直播内容
    if (_selectedNav == 6) {
      return [
        Expanded(
          child: LivePage(),
        )
      ];
    }
    
    // // 短剧页面：在主内容区域展示短剧内容
    // if (_selectedNav == 7) {
    //   return [
    //     Expanded(
    //       child: ShortPlayPage(),
    //     )
    //   ];
    // }
     
    // 首页模式：展示四栏热门
    if (_keyword == null && _selectedNav == 0) {
      return [
        Expanded(
          child: RefreshIndicator(
            onRefresh: _loadHomeSections,
            child: ListView(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              children: [
                if (_carouselItems.isNotEmpty)
                  _CarouselSection(
                    carouselItems: _carouselItems,
                    isWide: isWide,
                  ),
                const SizedBox(height: 6),
                _buildSection('热门电影', _hotMovies, isWide, _currentSite, onMore: () => _goToMenu('电影')),
                const SizedBox(height: 6),
                _buildSection('热门剧集', _hotTv, isWide, _currentSite, onMore: () => _goToMenu('剧集')),
                const SizedBox(height: 6),
                _buildSection('热门综艺', _hotVariety, isWide, _currentSite, onMore: () => _goToMenu('综艺')),
                const SizedBox(height: 6),
                _buildSection('热门动漫', _hotAnime, isWide, _currentSite, onMore: () => _goToMenu('动漫')),
                const SizedBox(height: 6),
                _buildSection('热门韩剧', _hotKorean, isWide, _currentSite, onMore: () => _goToMenu('韩剧')),
              ],
            ),
          ),
        )
      ];
    } else {
      return [
        Expanded(
          child: Column(
            children: [
              if (_selectedNav == 1)
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                  child: Row(
                    children: [
                      ChoiceChip(
                        label: const Text('热门电影'),
                        selected: _movieCategory == '热门电影',
                        onSelected: (selected) async {
                          if (selected && _movieCategory != '热门电影') {
                            setState(() {
                              _movieCategory = '热门电影';
                              _items = [];
                              _page = 1;
                            });
                            await _load(reset: true);
                          }
                        },
                      ),
                      const SizedBox(width: 8),
                      ChoiceChip(
                        label: const Text('Top250'),
                        selected: _movieCategory == 'Top250',
                        onSelected: (selected) async {
                          if (selected && _movieCategory != 'Top250') {
                            setState(() {
                              _movieCategory = 'Top250';
                              _items = [];
                              _page = 1;
                            });
                            await _load(reset: true);
                          }
                        },
                      ),
                    ],
                  ),
                ),
              Expanded(
                child: RefreshIndicator(
                  onRefresh: () => _load(reset: true),
                  child: GridView.builder(
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: isWide ? 6 : 3,
                      childAspectRatio: 0.66,
                      mainAxisSpacing: 12,
                      crossAxisSpacing: 12,
                    ),
                    itemCount: _items.length + 1,
                    itemBuilder: (context, index) {
                      if (index == _items.length) {
                        return Center(
                          child: _loading
                              ? const CircularProgressIndicator()
                              : FittedBox(
                                  fit: BoxFit.scaleDown,
                                  child: OutlinedButton(
                                    style: OutlinedButton.styleFrom(
                                      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                                      shape: const StadiumBorder(),
                                      minimumSize: const Size(100, 36),
                                    ),
                                    onPressed: () => _load(reset: false),
                                    child: const Text(
                                      '加载更多',
                                      maxLines: 1,
                                      softWrap: false,
                                    ),
                                  ),
                                ),
                        );
                      }
                      final item = _items[index];
                      return _PosterCard(
                        title: item.name,
                        subtitle: [item.typeName, item.year, item.area, item.remarks]
                            .where((e) => (e ?? '').isNotEmpty)
                            .join(' · '),
                        imageUrl: item.pic,
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (_) => DetailPage(site: _currentSite, id: item.id, keyword: item.name),
                            ),
                          );
                        },
                      );
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
      ];
    }
  }

  Widget _buildSection(String title, List<VodItem> list, bool isWide, VideoSite site, {VoidCallback? onMore}) {
    if (list.isEmpty) return const SizedBox.shrink();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.only(bottom: 8.0),
          child: Row(
            children: [
              Expanded(child: Text(title, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600))),
              if (onMore != null) TextButton(onPressed: onMore, child: const Text('查看更多')),
            ],
          ),
        ),
        SizedBox(
          height: isWide ? 240 : 180,
          child: ListView.separated(
            scrollDirection: Axis.horizontal,
            itemCount: list.length,
            separatorBuilder: (_, __) => const SizedBox(width: 8),
            itemBuilder: (context, i) {
              final item = list[i];
              return SizedBox(
                width: isWide ? 180 : 120,
                child: _PosterCard(
                  title: item.name,
                  subtitle: [item.typeName, item.year, item.area, item.remarks].where((e) => (e ?? '').isNotEmpty).join(' · '),
                  imageUrl: item.pic,
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (_) => DetailPage(site: site, id: item.id, keyword: item.name),
                      ),
                    );
                  },
                ),
              );
            },
          ),
        )
      ],
    );
  }
}

// 轮播图组件
class _CarouselSection extends StatefulWidget {
  final List<VodItem> carouselItems;
  final bool isWide;
  
  const _CarouselSection({
    required this.carouselItems,
    required this.isWide,
  });

  @override
  State<_CarouselSection> createState() => _CarouselSectionState();
}

class _CarouselSectionState extends State<_CarouselSection> {
  late PageController _pageController;
  late Timer _timer;
  int _currentPage = 0;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(viewportFraction: 1.0);
    _startAutoScroll();
  }

  @override
  void dispose() {
    _pageController.dispose();
    _timer.cancel();
    super.dispose();
  }

  void _startAutoScroll() {
    _timer = Timer.periodic(const Duration(seconds: 3), (timer) {
      if (widget.carouselItems.length > 1) {
        int nextPage = _currentPage + 1;
        if (nextPage >= widget.carouselItems.length) {
          nextPage = 0;
        }
        _pageController.animateToPage(
          nextPage,
          duration: const Duration(milliseconds: 500),
          curve: Curves.easeInOut,
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if (widget.carouselItems.isEmpty) {
      return const SizedBox.shrink();
    }
    
    return SizedBox(
      height: widget.isWide ? 260 : 180,
      child: PageView.builder(
        itemCount: widget.carouselItems.length,
        controller: _pageController,
        padEnds: false,
        pageSnapping: true,
        onPageChanged: (index) {
          setState(() {
            _currentPage = index;
          });
        },
        itemBuilder: (context, index) {
          final item = widget.carouselItems[index];
          return _CarouselCard(item: item, isWide: widget.isWide);
        },
      ),
    );
  }
}

class _CarouselCard extends StatelessWidget {
  final VodItem item;
  final bool isWide;
  
  const _CarouselCard({
    required this.item,
    required this.isWide,
  });

  @override
  Widget build(BuildContext context) {
    return Consumer<ThemeConfig>(
      builder: (context, themeConfig, child) {
        return InkWell(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (_) => DetailPage(
                  site: VideoSite(id: 'douban', name: '豆瓣', api: '', detail: '', isAdult: false),
                  id: item.id,
                  keyword: item.name,
                ),
              ),
            );
          },
          borderRadius: BorderRadius.circular(16),
          child: Container(
            width: double.infinity,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16),
              boxShadow: const [
                BoxShadow(color: Color(0x22000000), blurRadius: 12, offset: Offset(0, 6)),
              ],
            ),
            child: Stack(
              fit: StackFit.expand,
              children: [
                // 背景图片
                ClipRRect(
                  borderRadius: BorderRadius.circular(16),
                  child: item.pic == null
                      ? Container(
                          color: Colors.black26,
                          child: const Center(child: Icon(Icons.movie, size: 60, color: Colors.white)),
                        )
                      : CachedNetworkImage(
                          imageUrl: item.pic!,
                          imageBuilder: (context, provider) => isWide
                              ? Stack(
                                  fit: StackFit.expand,
                                  children: [
                                    // 背景：毛玻璃填充两侧空白
                                    Positioned.fill(
                                      child: ImageFiltered(
                                        imageFilter: ImageFilter.blur(sigmaX: 12, sigmaY: 12),
                                        child: Image(
                                          image: provider,
                                          fit: BoxFit.cover,
                                          filterQuality: FilterQuality.low,
                                        ),
                                      ),
                                    ),
                                    // 前景：原图保持完整比例
                                    Center(
                                      child: Image(
                                        image: provider,
                                        fit: BoxFit.contain,
                                        filterQuality: FilterQuality.high,
                                      ),
                                    ),
                                  ],
                                )
                              : Image(
                                  image: provider,
                                  fit: BoxFit.cover,
                                  filterQuality: FilterQuality.high,
                                ),
                          httpHeaders: const {
                            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                            'Referer': 'https://movie.douban.com/',
                          },
                          placeholder: (context, url) => Container(
                            color: Colors.black26,
                            child: const Center(child: CircularProgressIndicator(color: Colors.white)),
                          ),
                          errorWidget: (context, url, error) => Container(
                            color: Colors.black26,
                            child: const Center(child: Icon(Icons.movie, size: 60, color: Colors.white)),
                          ),
                        ),
                ),
                
                // 渐变遮罩
                Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(16),
                    gradient: LinearGradient(
                      begin: Alignment.bottomCenter,
                      end: Alignment.topCenter,
                      colors: [
                        Colors.black.withOpacity(0.8),
                        Colors.transparent,
                        Colors.transparent,
                        Colors.black.withOpacity(0.3),
                      ],
                    ),
                  ),
                ),
                
                // 内容
                Positioned(
                  bottom: 16,
                  left: 16,
                  right: 16,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        item.name,
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                          shadows: [
                            Shadow(blurRadius: 4, color: Colors.black87, offset: Offset(1, 1)),
                          ],
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      if (item.remarks != null)
                        Padding(
                          padding: const EdgeInsets.only(top: 4.0),
                          child: Text(
                            item.remarks!,
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 14,
                              shadows: [
                                Shadow(blurRadius: 4, color: Colors.black87, offset: Offset(1, 1)),
                              ],
                            ),
                          ),
                        ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
class _PosterCard extends StatelessWidget {
  final String title;
  final String subtitle;
  final String? imageUrl;
  final VoidCallback onTap;
  const _PosterCard({
    required this.title,
    required this.subtitle,
    required this.imageUrl,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return Consumer<ThemeConfig>(
      builder: (context, themeConfig, child) {
        return InkWell(
          onTap: onTap,
          borderRadius: BorderRadius.circular(12),
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
              boxShadow: const [
                BoxShadow(color: Color(0x11000000), blurRadius: 8, offset: Offset(0, 3)),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  child: ClipRRect(
                    borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
                    child: imageUrl == null
                        ? Container(color: Colors.black12, child: const Center(child: Icon(Icons.movie, size: 40)))
                        : CachedNetworkImage(
                            imageUrl: imageUrl!,
                            fit: BoxFit.cover,
                            width: double.infinity,
                            httpHeaders: const {
                              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                              'Referer': 'https://movie.douban.com/',
                            },
                            placeholder: (context, url) => Container(
                              color: Colors.black12,
                              child: const Center(child: CircularProgressIndicator()),
                            ),
                            errorWidget: (context, url, error) => Container(
                              color: Colors.black12,
                              child: const Center(child: Icon(Icons.movie, size: 40)),
                            ),
                          ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(title, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.w600, color: themeConfig.currentTextColor)),
                      const SizedBox(height: 4),
                      Text(subtitle, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: themeConfig.currentTextColor.withOpacity(0.7), fontSize: 12)),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}

class _PlayHistoryGridSection extends StatelessWidget {
  final List<PlayHistoryItem> playHistory;
  final void Function(PlayHistoryItem) onPlayItem;
  final VoidCallback onClearPlay;
  final VoidCallback onViewMore;
  final bool isWide;
  const _PlayHistoryGridSection({
    required this.playHistory,
    required this.onPlayItem,
    required this.onClearPlay,
    required this.onViewMore,
    required this.isWide,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.only(bottom: 8.0),
          child: Row(
            children: [
              Expanded(child: Text('播放历史', style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600))),
              TextButton(onPressed: onViewMore, child: const Text('查看更多')),
              const SizedBox(width: 8),
              TextButton(onPressed: onClearPlay, child: const Text('清空')),
            ],
          ),
        ),
        SizedBox(
          height: isWide ? 240 : 180,
          child: ListView.separated(
            scrollDirection: Axis.horizontal,
            itemCount: playHistory.length,
            separatorBuilder: (_, __) => const SizedBox(width: 8),
            itemBuilder: (context, i) {
              final item = playHistory[i];
              return SizedBox(
                width: isWide ? 180 : 120,
                child: _HistoryPosterCard(
                  title: item.title,
                  subtitle: item.siteName ?? '',
                  imageUrl: item.cover,
                  onTap: () => onPlayItem(item),
                ),
              );
            },
          ),
        )
      ],
    );
  }
}

class _HistoryPosterCard extends StatelessWidget {
  final String title;
  final String subtitle;
  final String? imageUrl;
  final VoidCallback onTap;
  const _HistoryPosterCard({
    required this.title,
    required this.subtitle,
    required this.imageUrl,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return Consumer<ThemeConfig>(
      builder: (context, themeConfig, child) {
        return InkWell(
          onTap: onTap,
          borderRadius: BorderRadius.circular(12),
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
              boxShadow: const [
                BoxShadow(color: Color(0x11000000), blurRadius: 8, offset: Offset(0, 3)),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  child: ClipRRect(
                    borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
                    child: imageUrl == null || imageUrl!.isEmpty
                        ? Container(color: Colors.black12, child: const Center(child: Icon(Icons.movie, size: 40)))
                        : CachedNetworkImage(
                            imageUrl: imageUrl!,
                            fit: BoxFit.cover,
                            width: double.infinity,
                            httpHeaders: const {
                              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                              'Referer': 'https://movie.douban.com/',
                            },
                            placeholder: (context, url) => Container(
                              color: Colors.black12,
                              child: const Center(child: CircularProgressIndicator()),
                            ),
                            errorWidget: (context, url, error) => Container(
                              color: Colors.black12,
                              child: const Center(child: Icon(Icons.movie, size: 40)),
                            ),
                          ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(title, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.w600, color: themeConfig.currentTextColor)),
                      const SizedBox(height: 4),
                      Text(subtitle, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: themeConfig.currentTextColor.withOpacity(0.7), fontSize: 12)),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
 
